<template>
  <div class="app-container">
    <!-- 搜索区域：优化样式和响应式布局 -->
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      label-width="80px"
      class="search-form"
    >
      <el-form-item label="来访姓名" prop="visitorName">
        <el-input
          v-model="queryParams.visitorName"
          placeholder="请输入来访人姓名"
          clearable
          @keyup.enter="handleQuery"
          class="input-with-margin"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号"
          clearable
          @keyup.enter="handleQuery"
          class="input-with-margin"
        />
      </el-form-item>
      <el-form-item label="来访时间">
        <el-date-picker
          v-model="daterangeVisitTime"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          class="date-range-picker"
        ></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="Search"
          @click="handleQuery"
          class="btn-with-margin"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 筛选标签 + 来访登记 放在同一行 -->
    <div class="filter-and-button-container">
      <!-- 筛选标签栏 -->
      <div class="filter-tags">
        <el-button
          type="text"
          :class="{ 'active-filter': currentFilter === '' }"
          @click="handleFilter('')"
          class="filter-btn"
          >全部</el-button
        >
        <el-button
          type="text"
          :class="{ 'active-filter': currentFilter === '参观来访' }"
          @click="handleFilter('参观来访')"
          class="filter-btn"
          >参观来访</el-button
        >
        <el-button
          type="text"
          :class="{ 'active-filter': currentFilter === '探访来访' }"
          @click="handleFilter('探访来访')"
          class="filter-btn"
          >探访来访</el-button
        >
      </div>

      <!-- 来访登记按钮 -->
      <div class="action-button">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:visitor_registration:add']"
          class="add-button"
          >来访登记</el-button
        >
      </div>
    </div>

    <!-- 表格区域：添加操作列 -->
    <el-table
      v-loading="loading"
      :data="visitor_registrationList"
      border
      stripe
      class="custom-table"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="id" width="80" />
      <el-table-column label="来访类型" align="center" prop="visitorType">
        <template #default="scope">
          <el-tag
            :type="scope.row.visitorType === '参观来访' ? 'success' : 'warning'"
          >
            {{ scope.row.visitorType }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="来访姓名"
        align="center"
        prop="visitorName"
        width="120"
      />
      <el-table-column label="手机号" align="center" prop="phone" width="150" />
      <el-table-column
        label="老人姓名"
        align="center"
        prop="elderly.name"
        width="120"
      />
      <el-table-column
        label="来访时间"
        align="center"
        prop="visitTime"
        width="160"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.visitTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="创建人"
        align="center"
        prop="sysUser.userName"
        width="120"
      />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      />
      <el-table-column label="操作" align="center" width="120" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="View"
            @click="handleView(scope.row)"
            v-hasPermi="['system:visitor_registration:view']"
            >查看</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加来访登记对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form
        ref="visitor_registrationRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="来访类型" prop="visitorType">
          <el-radio-group v-model="form.visitorType">
            <el-radio :label="'参观来访'">参观来访</el-radio>
            <el-radio :label="'探访来访'">探访来访</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="来访姓名" prop="visitorName">
          <el-input v-model="form.visitorName" placeholder="请输入来访人姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="老人姓名" prop="elderlyId">
          <el-input v-model="form.elderlyId" placeholder="请输入老人姓名" />
        </el-form-item>
        <el-form-item label="来访时间" prop="visitTime">
          <el-date-picker
            clearable
            v-model="form.visitTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择来访时间"
            style="width: 100%"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="创建人" prop="creator">
          <el-input v-model="form.creator" placeholder="请输入创建人" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog
      title="来访登记详情"
      v-model="viewOpen"
      width="500px"
      append-to-body
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="来访类型">{{
          viewForm.visitorType
        }}</el-descriptions-item>
        <el-descriptions-item label="来访姓名">{{
          viewForm.visitorName
        }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{
          viewForm.phone
        }}</el-descriptions-item>
        <el-descriptions-item label="老人姓名">{{
          viewForm.elderly?.name
        }}</el-descriptions-item>

        <el-descriptions-item label="来访时间">{{
          parseTime(viewForm.visitTime)
        }}</el-descriptions-item>
        <el-descriptions-item label="创建人">{{
          viewForm.sysUser?.userName || viewForm.creator
        }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{
          parseTime(viewForm.createTime)
        }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="viewOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Visitor_registration">
import {
  listVisitor_registration,
  addVisitor_registration,
  getVisitor_registration,
} from "@/api/system/visitor_registration";
import { getElderly } from "@/api/system/elderly"; // 导入获取老人信息的API
import { getUser } from "@/api/system/user"; // 导入获取用户信息的API
import { parseTime } from "@/utils/ruoyi";

const { proxy } = getCurrentInstance();

const visitor_registrationList = ref([]);
const open = ref(false);
const viewOpen = ref(false); // 新增查看详情弹窗开关
const loading = ref(true);
const total = ref(0);
const title = ref("");
const daterangeVisitTime = ref([]);
const currentFilter = ref(""); // 当前选中的筛选类型，空字符串表示"全部"
const viewForm = ref({}); // 新增查看详情表单数据

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    visitorName: null,
    phone: null,
    visitTime: null,
    visitorType: null, // 来访类型筛选参数
    extraField2: null,
  },
  rules: {
    visitorType: [
      { required: true, message: "来访类型不能为空", trigger: "change" },
    ],
    visitorName: [
      { required: true, message: "来访人姓名不能为空", trigger: "blur" },
    ],
    phone: [
      { required: true, message: "手机号不能为空", trigger: "blur" },
      {
        pattern: /^1[3-9]\d{9}$/,
        message: "请输入正确的手机号码格式",
        trigger: "blur",
      }, // 新增手机号格式验证
    ],
    visitTime: [
      { required: true, message: "来访时间不能为空", trigger: "change" }, // 修改为change触发
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询来访登记列表 */
function getList() {
  loading.value = true;

  // 处理日期范围
  const params = {};
  if (daterangeVisitTime.value && daterangeVisitTime.value.length === 2) {
    params["beginVisitTime"] = daterangeVisitTime.value[0];
    params["endVisitTime"] = daterangeVisitTime.value[1];
  }

  // 根据当前筛选类型设置来访类型参数
  if (currentFilter.value) {
    queryParams.value.visitorType = currentFilter.value;
  } else {
    queryParams.value.visitorType = null;
  }

  // 合并查询参数
  const requestParams = {
    ...queryParams.value,
    params,
  };

  listVisitor_registration(requestParams)
    .then((response) => {
      visitor_registrationList.value = response.rows || []; // 增加空数组默认值
      total.value = response.total || 0;
      loading.value = false;
    })
    .catch(() => {
      visitor_registrationList.value = [];
      total.value = 0;
      loading.value = false;
      proxy.$modal.msgError("获取数据失败，请重试");
    });
}

/** 查看详情按钮操作 */
function handleView(row) {
  getVisitor_registration(row.id)
    .then((response) => {
      viewForm.value = response.data;

      // 如果没有老人姓名但有elderlyId，则通过外键查询老人信息
      if (!viewForm.value.elderly?.name && viewForm.value.elderlyId) {
        getElderly(viewForm.value.elderlyId)
          .then((elderlyRes) => {
            // 更新老人信息到视图表单
            if (elderlyRes.data) {
              viewForm.value.elderly = elderlyRes.data;
            }
          })
          .catch(() => {
            console.log("获取老人信息失败");
          });
      }

      // 如果没有创建人姓名但有creator（用户ID），则通过外键查询用户信息
      if (!viewForm.value.sysUser?.userName && viewForm.value.creator) {
        getUser(viewForm.value.creator)
          .then((userRes) => {
            // 更新用户信息到视图表单
            if (userRes.data) {
              viewForm.value.sysUser = userRes.data;
            }
          })
          .catch(() => {
            console.log("获取创建人信息失败");
          });
      }

      viewOpen.value = true;
    })
    .catch(() => {
      proxy.$modal.msgError("获取详情失败");
    });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    visitorType: null,
    visitorName: null,
    phone: null,
    elderlyId: null,
    visitTime: null,
    creator: null,
    createTime: null,
    status: null,
    extraField1: null,
    extraField2: null,
  };
  if (proxy && proxy.resetForm) {
    proxy.resetForm("visitor_registrationRef");
  }
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeVisitTime.value = [];
  currentFilter.value = ""; // 重置筛选状态
  if (proxy && proxy.resetForm) {
    proxy.resetForm("queryRef");
  }
  handleQuery();
}

/** 筛选标签点击操作 */
function handleFilter(type) {
  currentFilter.value = type;
  queryParams.value.pageNum = 1;
  getList();
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加来访登记";
}

/** 提交按钮 */
function submitForm() {
  if (!proxy || !proxy.$refs["visitor_registrationRef"]) return;

  proxy.$refs["visitor_registrationRef"].validate((valid) => {
    if (valid) {
      addVisitor_registration(form.value)
        .then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        })
        .catch(() => {
          proxy.$modal.msgError("新增失败，请重试");
        });
    }
  });
}

// 初始化加载
getList();
</script>

<style scoped>
/* 搜索表单样式优化 */
.search-form {
  margin-bottom: 16px;
  padding: 12px;
  background: transparent;
  border-radius: 4px;
}

.input-with-margin {
  margin-right: 8px;
  width: 180px;
}

.btn-with-margin {
  margin-right: 8px;
}

.date-range-picker {
  width: 280px;
}

/* 筛选和按钮区域优化 */
.filter-and-button-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 12px;
  background: transparent;
  border-radius: 4px;
}

.filter-tags {
  display: flex;
  align-items: center;
  gap: 12px;
  background: transparent;
  padding: 2px;
  border-radius: 4px;
}

.filter-btn {
  min-width: 80px;
  font-size: 14px;
  color: #606266;
  background-color: #fff;
  transition: all 0.3s ease;
  border-radius: 3px;
}

.filter-btn:hover {
  color: #409eff;
  background-color: #ecf5ff;
}

.active-filter {
  color: #fff !important;
  background-color: #409eff !important;
}

.active-filter:hover {
  color: #fff !important;
  background-color: #66b1ff !important;
}

.add-button {
  padding: 8px 20px;
  font-size: 14px;
}

/* 表格样式优化 */
.custom-table {
  margin-bottom: 16px;
}

.custom-table tr:hover {
  background-color: #f5f7fa;
}

/* 响应式设计优化 */
@media (max-width: 1024px) {
  .search-form .el-form-item {
    margin-bottom: 10px;
  }

  .input-with-margin,
  .date-range-picker {
    width: 100%;
    margin-right: 0;
  }
}

@media (max-width: 768px) {
  .filter-and-button-container {
    flex-direction: column;
    gap: 12px;
  }

  .filter-tags {
    flex-wrap: wrap;
    justify-content: center;
  }
}
</style>